package ce.com.cenewbluesdk.uitl;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothDevice;
import android.os.Build;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 蓝牙配对函数
 * @see <a href="http://my.oschina.net/billowworld/blog/62975?fromerr=3DeOOYCz">如何实现android蓝牙开发 自动配对连接,并不弹出提示框</>
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public class BluetoothDeviceReflect {
    public static final int PAIRING_VARIANT_CONSENT = 3;
    public static final int PAIRING_VARIANT_PASSKEY_CONFIRMATION = BluetoothDevice.PAIRING_VARIANT_PASSKEY_CONFIRMATION;// 2
    public static final int PAIRING_VARIANT_PIN = BluetoothDevice.PAIRING_VARIANT_PIN;// 0

    /**
     * 创建配对,
     * 因为api19中这些方法去掉了@hide标签, 故可以直接调用
     */
    public static boolean createBond(BluetoothDevice device) {
        try {
            return device.createBond();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /** 设置pin */
    public static boolean setPin(BluetoothDevice device, byte[] bin) {
        try {
            return device.setPin(bin);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /** 确定配对 */
    public static boolean setPairingConfirmation(BluetoothDevice device, boolean confirm) {
        try {
            return device.setPairingConfirmation(confirm);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 与设备解除配对
     * 参考源码：platform/packages/apps/Settings.git/Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java
     * 这些方法都被@hide了, 需要反射调用
     */
    public static boolean removeBond(BluetoothDevice device) {
        return invokeMethod(device, "removeBond");
    }

    /**
     * 用户取消配对
     * 在源码:(platform/packages/apps/Settings.git/Settings/src/com/android/settings/bluetooth/BluetoothPairingDialog.java)
     * 中, 当用户点击取消时调用
     */
    public static boolean cancelPairingUserInput(BluetoothDevice device) {
        return invokeMethod(device, "cancelPairingUserInput");
    }

    /**
     * 取消配对
     * 在源码:(platform/packages/apps/Settings.git/Settings/src/com/android/settings/bluetooth/)
     * 中, 用于在解绑前, 取消正在进行的配对
     */
    public static boolean cancelBondProcess(BluetoothDevice device) {
        return invokeMethod(device, "cancelBondProcess");
    }

    private static boolean invokeMethod(BluetoothDevice device, String methodName) {
        try {
            final Method method = BluetoothDevice.class.getMethod(methodName);
            return (boolean) method.invoke(device);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return false;
    }
}